import { defineStore } from "pinia";
import userInfoApi from "@/api/user/userInfo";
import type { tokenData, loginData, userInfoDate } from "@/api/user/userInfo";
import type {RouteRecordRaw} from 'vue-router'
import { staticRoutes ,allAsyncRoutes,anyRoute} from "@/router/routes";
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
// 初始化用户信息,因为重新登录时要清空原值，可进行覆盖
function initUserInfo(): userInfoDate{
  return {
    routes: [],
    buttons: [],
    rules: [],
    name: "",
    avatar: "",
  };
}
// 状态也需要限制类型
interface userStoreStateData {
  token: string;
  userInfo: userInfoDate;
  menuRoutes:Array<RouteRecordRaw>
}

//这个函数就是专门让用户登录后从配置的所有异步路由数组中过滤自己的异步路由
function filterAsyncRoutes(allAsyncRoutes:RouteRecordRaw[],routeNames:string[]){
  let asyncRoutes = allAsyncRoutes.filter(item=>{
    if(routeNames.indexOf(item.name as string) !== -1){
      if(item.children && item.children.length){
        item.children = filterAsyncRoutes(item.children,routeNames)
      }
      return true
    }
  })
  return asyncRoutes
}

// 往路由器内部动态添加注册路由
function addRoutes(routes:RouteRecordRaw[]){
  routes.forEach(item=>{
    router.addRoute(item)
  })
}

// 退出登录时重置路由
function resetRoutes(){
  // 1、先把路由器当中的所有路由删除 先获取所有路由，再遍历删除
  let routes = router.getRoutes()
  routes.forEach(item=>{
    router.removeRoute(item.name as string)
  })
addRoutes(staticRoutes)
   // 2、在给路由器当中动态添加上staticRoutes
}


export const useUserInfoStore = defineStore("userInfo", {
  state: (): userStoreStateData => {
    return {
      token: localStorage.getItem("token_key") || "",
      userInfo: {
        routes: [],
        buttons: [],
        rules: [],
        name: "",
        avatar: "",
      },
      menuRoutes:[]
    };
  },
  actions: {
    // 登录请求
    async login(userInfo: loginData) {
      try {
        const result = await userInfoApi.userLogin(userInfo);
        this.token = result.token;
        localStorage.setItem("token_key", result.token);
        return "ok";
      } catch (error) {
        return Promise.reject("登录失败");
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const result = await userInfoApi.getUserInfo();
        this.userInfo = result;
        // 从返回的routes中的所有异步路由中过滤出自己的路由
        let routeNames = result.routes
        // 过滤获取用户自己的异步路由
        let userAsyncRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes),routeNames)
        // 添加异步和路由和任意路由
        addRoutes(userAsyncRoutes.concat(anyRoute))
        // 为了显示菜单，要将state中的菜单数据做修改
        this.menuRoutes = staticRoutes.concat(userAsyncRoutes,anyRoute)
        return "ok";
      } catch (error) {
        return Promise.reject("获取用户信息失败");
      }
    },

    // 定义一个重置函数，因为permission文件中需要用重置
    async reset() {
      this.token = "";
      localStorage.removeItem("token_key");
      Object.assign(this.userInfo,initUserInfo()) 
    },
    // 退出登录
    async logout() {
      try {
        await userInfoApi.userLogout();
        // 退出登录时重置路由为静态组件
        resetRoutes()
        // 清空所有token和用户信息
        this.reset();
        return "ok";
      } catch (error) {
        return Promise.reject("退出登录失败");
      }
    },
  },
  getters: {},
});
// import { defineStore } from 'pinia';
// import { getToken, removeToken, setToken } from '../utils/token-utils';
// import type { UserInfoState } from './interface';
// import {ElMessage} from 'element-plus'
// import {staticRoutes} from '@/router/routes'

// /**
//  * 用户信息
//  * @methods setUserInfos 设置用户信息
//  */
// export const useUserInfoStore = defineStore('userInfo', {

// 	state: (): UserInfoState => ({
//     token: getToken() as string,
//     name: '',
//     avatar: '',
//     menuRoutes: []
//   }),

// 	actions: {
//     login (username: string, password: string) {
//       return new Promise((resolve, reject) => {
//         setTimeout(() => {
//           if (username==='admin' && password==='111111') {
//             const token = 'token-atguigu'
//             setToken(token)
//             this.token = token
//             resolve(token)
//           } else {
//             reject(new Error('用户名或密码错误!'))
//             ElMessage.error('用户名或密码错误!')
//           }
//         }, 1000)
//       })
//     },

//     getInfo () {
//       return new Promise((resolve, reject) => {
//         setTimeout(() => {
//           this.name = 'admin'
//           this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
//           this.menuRoutes = staticRoutes
//           resolve({name: this.name, avatar: this.avatar, token: this.token})
//         }, 1000)
//       })
//     },

//     reset () {
//       // 删除local中保存的token
//       removeToken()
//       // 提交重置用户信息的mutation
//       this.token = ''
//       this.name = ''
//       this.avatar = ''
//     },
// 	},
// });
